package org.gg.boom.modules.sys.controller;

import com.alibaba.fastjson2.JSONObject;
import org.gg.boom.common.controller.BaseController;
import org.gg.boom.common.model.Response;
import org.gg.boom.common.utils.SecurityUtils;
import org.gg.boom.kernel.web.service.SysLoginService;
import org.gg.boom.kernel.web.service.SysPermissionService;
import org.gg.boom.modules.sys.model.LoginBody;
import org.gg.boom.modules.sys.model.entity.SysMenu;
import org.gg.boom.modules.sys.model.entity.SysUser;
import org.gg.boom.modules.sys.model.vo.SysMenuResult;
import org.gg.boom.modules.sys.model.vo.SysUserResult;
import org.gg.boom.modules.sys.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 */
@RestController
public class SysLoginController extends BaseController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private SysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public Response login(@RequestBody LoginBody loginBody) {
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        return success(token);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public Response getInfo() {
        SysUserResult user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        JSONObject result = new JSONObject();
        result.put("user", user);
        result.put("roles", roles);
        result.put("permissions", permissions);
        return success(result);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public Response getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenuResult> menus = menuService.selectMenuTreeByUserId(userId);
        return Response.success(menuService.buildMenus(menus));
    }
}
